Page({
  data: {
    caseReason: '',
    topic: '',
    organizerWill: '',
    opinionContent: '',
    fileList: [],
    typeIndex: null,
    publicOpnionsTypes: [
      '医疗健康类',
      '教育科技类',
      '文化体育类',
      '城市建设类',
      '环境保护类',
      '社会治理类',
      '经济发展类',
      '其他类'
    ],
    isPublic: true,
    cosigners: [],
  },

  onLoad: function (options) {
    // 页面加载时的逻辑
  },

  handleTitleInput: function (e) {
    this.setData({
      caseReason: e.detail.value
    });
  },

  handleTopicInput: function (e) {
    this.setData({
      topic: e.detail.value
    });
  },

  handleOrganizerWillInput: function (e) {
    this.setData({
      organizerWill: e.detail.value
    });
  },

  handleContentInput: function (e) {
    this.setData({
      opinionContent: e.detail.value
    });
  },
  addCosigner() {
    wx.showModal({
      title: '添加联名人',
      editable: true,
      placeholderText: '请输入联名人ID',
      success: (res) => {
        if (res.confirm) {
          // 判断输入内容是否为空或者只包含空格
          if (!res.content || res.content.trim() === '') {
            wx.showToast({
              title: '联名人ID不能为空',
              icon: 'none',
              duration: 2000
            });
            return;
          }

          const input = res.content.trim(); // 去除首尾空格

          // 检查是否为纯数字
          if (!/^\d+$/.test(input)) {
            wx.showToast({
              title: '联名人ID格式错误，只能输入数字',
              icon: 'none',
              duration: 2000
            });
            return;
          }

          // 检查是否超过int最大值
          const numValue = parseInt(input);
          if (numValue > 2147483647) {
            wx.showToast({
              title: '联名人ID超出有效范围',
              icon: 'none',
              duration: 2000
            });
            return;
          }

          const cosigners = this.data.cosigners;

          // 检查是否已存在相同ID
          const isDuplicate = cosigners.includes(input);
          if (isDuplicate) {
            wx.showToast({
              title: '该联名人已添加',
              icon: 'none',
              duration: 2000
            });
            return;
          }

          // 添加到数组中
          cosigners.push(input);
          this.setData({
            cosigners
          });
        }
      }
    });
  },

  // 删除联名人
  deleteCosigner(e) {
    const index = e.currentTarget.dataset.index
    const cosigners = this.data.cosigners
    cosigners.splice(index, 1)
    this.setData({
      cosigners
    })
  },

  // 处理文件上传
  handleUpload() {
    wx.chooseMessageFile({
      count: 4,
      type: 'file',
      success: (res) => {
        const files = res.tempFiles;
        const maxTotalSize = 50 * 1024 * 1024; // 总计50MB限制

        // 计算选择的所有文件的总大小
        const totalSize = files.reduce((sum, file) => sum + file.size, 0);

        // 检查总大小是否超过限制
        if (totalSize > maxTotalSize) {
          wx.showModal({
            title: '文件过大',
            content: `选择的文件总大小为${this.formatFileSize(totalSize)}，超过50MB限制，请重新选择`,
            showCancel: false
          });
          return;
        }

        // 处理每个文件
        files.forEach(file => {
          // 显示文件在列表中
          const newFile = {
            name: file.name,
            size: this.formatFileSize(file.size),
            path: file.path,
            uploading: true
          };

          this.setData({
            fileList: [...this.data.fileList, newFile]
          });

          const app = getApp();
          // 上传文件
          app.userRequest.uploadFiles(file.path, {
            fileName: file.name
          }).then(res => {
            console.log('上传成功', res);

            // 更新文件状态
            const updatedList = this.data.fileList.map(item => {
              if (item.path === file.path) {
                return {
                  ...item,
                  uploading: false,
                  uploaded: true,
                  url: res.data.data
                };
              }
              return item;
            });

            this.setData({
              fileList: updatedList
            });

            wx.showToast({
              title: '上传成功',
              icon: 'success'
            });
          }).catch(err => {
            console.error('上传失败', err);

            // 从文件列表中移除失败的文件
            const updatedList = this.data.fileList.filter(item =>
              item.path !== file.path
            );

            this.setData({
              fileList: updatedList
            });

            wx.showModal({
              title: '上传失败',
              content: `文件 "${file.name}" 上传失败，请重试`,
              showCancel: false
            });
          });
        });
      },
      fail: () => {
        console.log('文件上传异常');
      }
    });
  },

  // 删除文件
  deleteFile(e) {
    const index = e.currentTarget.dataset.index
    const fileList = this.data.fileList
    fileList.splice(index, 1)
    this.setData({
      fileList
    })
  },
    // 格式化文件大小
    formatFileSize(size) {
      if (size < 1024) {
        return size + 'B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(1) + 'KB'
      } else {
        return (size / 1024 / 1024).toFixed(1) + 'MB'
      }
    },
  
  handleTypeChange: function (e) {
    this.setData({
      typeIndex: e.detail.value
    });
  },

  handlePublicChange: function (e) {
    this.setData({
      isPublic: e.detail.value === '1'
    });
  },

  submitPublicOpnions: function () {
    // 表单验证
    if (!this.data.caseReason.trim()) {
      wx.showToast({
        title: '请输入标题',
        icon: 'none'
      });
      return;
    }

    if (!this.data.opinionContent.trim()) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      });
      return;
    }

    if (this.data.typeIndex === null) {
      wx.showToast({
        title: '请选择类型',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '提交中...'
    });

    var data1 = {
          caseReason: this.data.caseReason,
          topic: this.data.topic,
          organizerWill: this.data.organizerWill,
          opinionContent: this.data.opinionContent,
          opinionType: this.data.publicOpnionsTypes[this.data.typeIndex],
          isPublic: this.data.isPublic ? 1 : 0,
          filePath: this.data.fileList,
          signersId: this.data.cosigners
    }

    const app = getApp()
    app.civilApi.submitCivils(data1).then(
      res => {
        console.log(res)
        if (res.data.code === 200) {
          wx.hideLoading()
          wx.showToast({
            title: '提交成功'
          })
          // 模拟提交
          setTimeout(() => {
            // 提交成功后返回上一页
            wx.navigateBack()
          }, 1500)
        }else {
          wx.hideLoading()
          wx.showToast({
            title: res.data.message,
            icon:'none'
          })
        }
      })
  }
});